# -*- coding: utf-8 -*-
"""
Author: chen xi
Date: 2025/9/12 上午10:58
File: ssh_script.py
"""

import paramiko
import time


def ssh_exec_commands(host, port, username, password, commands):
	client = paramiko.SSHClient()
	client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
	
	try:
		print(f"正在连接 {host}:{port} ...")
		client.connect(hostname=host, port=port, username=username, password=password, timeout=10)
		print("✅ SSH 连接成功\n")
		
		for cmd in commands:
			print(f"执行命令: {cmd}")
			stdin, stdout, stderr = client.exec_command(cmd)
			channel = stdout.channel  # 获取底层 channel
			
			# 非阻塞轮询输出，最多等 5 秒
			start_time = time.time()
			while not channel.closed:
				# 有标准输出
				if channel.recv_ready():
					data = channel.recv(1024).decode('utf-8')
					if data:
						print(f"  | {data.strip()}")
				
				# 有错误输出
				if channel.recv_stderr_ready():
					data = channel.recv_stderr(1024).decode('utf-8')
					if data:
						print(f"  ❌ 错误: {data.strip()}")
				
				# 超时退出（关键！）
				if time.time() - start_time > 5:
					print("  ⚠️  超时，跳过等待...")
					break
				
				time.sleep(2)
			
			# 强制关闭 channel
			channel.close()
			print("  ✅ 命令已发送，通道关闭")
			print("-" * 50)
	
	except paramiko.AuthenticationException:
		print("❌ 认证失败，请检查用户名或密码")
	except paramiko.SSHException as e:
		print(f"❌ SSH 异常: {e}")
	except Exception as e:
		print(f"❌ 连接失败: {e}")
	finally:
		client.close()
		print("🔌 SSH 连接已关闭")


# ======================================
# 使用示例
# ======================================

if __name__ == "__main__":
	time_wait = 10
	
	baohuo_ips = [
		"8.130.108.109",
		# "47.112.205.147",
		# "47.112.206.168",
		# "47.112.10.56",
		# "47.112.205.245",
		# "47.112.199.191",
		# "47.112.204.184",
		# "47.112.196.240",
		# "47.112.205.75"
	]
	# cesu_ips = [
	# 	"47.112.205.112"
	# ]
	
	PORT = 22
	USER = "root"
	PASS = "ZOWELL#2511101549"  # 建议改用密钥登录
	
	# 运行保活与唤醒脚本
	baohuo_cmds = [
		"mkdir ~/test/log",
		'pkill -f iot_wakeup_with_latency_v2.py;pkill -f app_to_server_wake_up_v2.py;pkill -f tcp_stress_test_speed.py;pkill -f mass_tcp_client_with_reconnect.py',
		"cd ~/test && source .venv/bin/activate && nohup python3 -u iot_wakeup_with_latency_v2.py > ./log/iot_v2.log 2>&1 < /dev/null &"
	]
	
	# 运行测速脚本
	cesu_cmds = [
		"mkdir ~/test/log",
		'pkill -f iot_wakeup_with_latency_v2.py;pkill -f app_to_server_wake_up_v2.py;pkill -f tcp_stress_test_speed.py;pkill -f mass_tcp_client_with_reconnect.py',
		"cd ~/test && source .venv/bin/activate && nohup python3 -u tcp_stress_test_speed.py > ./log/tcp_stress_test_speed.log 2>&1 < /dev/null &",
		"cd ~/test && source .venv/bin/activate && nohup python3 -u mass_tcp_client_with_reconnect.py > ./log/mass_tcp_client_with_reconnect.log 2>&1 < /dev/null &",
		"cd ~/test && source .venv/bin/activate && nohup python3 -u app_to_server_wake_up_v2.py > ./log/app_to_server_wake_up_v2.log 2>&1 < /dev/null &",
	]

	for HOST in baohuo_ips:
		print(f"\n{'=' * 60}")
		print(f"🚀 正在操作服务器: {HOST}")
		print(f"{'=' * 60}")
		ssh_exec_commands(HOST, PORT, USER, PASS, baohuo_cmds)
		print(f"✅ {HOST} 执行完成，等待 {time_wait} 秒...")
		time.sleep(time_wait)  # 现在可以正常执行了！
	
	# for HOST in cesu_ips:
	# 	print(f"\n{'=' * 60}")
	# 	print(f"🚀 正在操作服务器: {HOST}")
	# 	print(f"{'=' * 60}")
	# 	ssh_exec_commands(HOST, PORT, USER, PASS, cesu_cmds)
	# 	print(f"✅ {HOST} 执行完成，等待 {time_wait} 秒...")
	# 	time.sleep(time_wait)  # 现在可以正常执行了！
